const DB_NAME = 'reservoir'
const DB_VERSION = 1 // Use a long long for this value (don't use a float)
const DB_STORE_NAME = 'model_glb'

export default class DBUtil {

  async get(db, url, onProgress) {
    const getRequest = db
      .transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).get(url)

    const that = this

    return new Promise((resolve, reject) => {
      getRequest.onsuccess = function (event) {
        const modelFile = event.target.result
        // 假如已经有缓存了 直接用缓存

        if (modelFile) {
          resolve(modelFile.blob)
        } else {
          // 假如没有缓存 请求新的模型存入
          that.put(db, url, onProgress).then((blob) => {
            resolve(blob)
          }).catch(() => {
            reject()
          })
        }
      }
      getRequest.onerror = function (event) {
        console.log('error', event)
        reject()
      }
    })
  }

  async put(db, url, onProgress) {
    let rs = await fetch(url, { method: 'get' })

    if (rs.status === 200) {
      let blob = null

      try {
        blob = await rs.arrayBuffer()
      } catch (e) {
        console.log('请求arrayBuffer失败,用blob方式')
        rs = await fetch(url, { method: 'get' })
        blob = await rs.blob()
      }
      const obj = {
        ssn: url
      }

      obj.blob = new Blob([blob])
      const inputRequest = db
        .transaction([DB_STORE_NAME], 'readwrite')
        .objectStore(DB_STORE_NAME)
        .add(obj)

      return new Promise((resolve, reject) => {
        inputRequest.onsuccess = function () {
          console.log('glb数据添加成功')
          resolve(obj.blob)
        }
        inputRequest.onerror = function (evt) {
          console.log('glb数据添加失败', evt)
          reject()
        }
      })
    }
  }

  initDataBase() {
    if (!window.indexedDB) {
      console.log("Your browser doesn't support a stable version of IndexedDB.")
      return
    }
    const request = indexedDB.open(DB_NAME, DB_VERSION)

    return new Promise((resolve, reject) => {
      request.onerror = function () {
        console.log('error: create db error')
        reject()
      }
      request.onupgradeneeded = function (evt) {
        evt.currentTarget.result.createObjectStore(
          DB_STORE_NAME, { keyPath: 'ssn' })
      }
      request.onsuccess = function (evt) {
        console.log('onsuccess: create db success ')
        resolve(evt.target.result)
      }
    })
  }
}